using MediatR;
using Microsoft.AspNetCore.Mvc;
using S.M.SmartMedical.API.Read.Application.Query;
using S.M.SmartMedical.Domain.DTOs;
using S.M.SmartMedical.ErrorCode;

namespace S.M.SmartMedical.API.Read.Controllers
{
    /// <summary>
    /// 医院院区控制器
    /// 提供院区相关的查询接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class HospitalAreaController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<HospitalAreaController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者</param>
        /// <param name="logger">日志记录器</param>
        public HospitalAreaController(IMediator mediator, ILogger<HospitalAreaController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 获取自助开单院区列表
        /// </summary>
        /// <param name="userLongitude">用户当前位置经度（可选）</param>
        /// <param name="userLatitude">用户当前位置纬度（可选）</param>
        /// <param name="searchKeyword">搜索关键词（可选）</param>
        /// <param name="onlySelfServiceEnabled">是否只返回支持自助开单的院区，默认为true</param>
        /// <returns>院区列表</returns>
        [HttpGet("self-service")]
        [ProducesResponseType(typeof(APIResult<List<HospitalAreaDto>>), 200)]
        public async Task<ActionResult<APIResult<List<HospitalAreaDto>>>> GetSelfServiceHospitalAreas(
            [FromQuery] decimal? userLongitude = null,
            [FromQuery] decimal? userLatitude = null,
            [FromQuery] string? searchKeyword = null,
            [FromQuery] bool onlySelfServiceEnabled = true)
        {
            try
            {
                _logger.LogInformation("接收到获取自助开单院区列表请求，搜索关键词：{SearchKeyword}，用户位置：({Latitude}, {Longitude})", 
                    searchKeyword, userLatitude, userLongitude);

                var query = new GetHospitalAreasQuery
                {
                    UserLongitude = userLongitude,
                    UserLatitude = userLatitude,
                    SearchKeyword = searchKeyword,
                    OnlySelfServiceEnabled = onlySelfServiceEnabled
                };

                var result = await _mediator.Send(query);
                
                _logger.LogInformation("成功处理获取自助开单院区列表请求，返回 {Count} 个院区", result.Data?.Count ?? 0);
                
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理获取自助开单院区列表请求时发生错误");
                return StatusCode(500, new APIResult<List<HospitalAreaDto>>
                {
                    Code = APIEnum.Fail,
                    Message = "服务器内部错误，请稍后重试",
                    Data = new List<HospitalAreaDto>()
                });
            }
        }

        /// <summary>
        /// 获取所有院区列表（包括不支持自助开单的院区）
        /// </summary>
        /// <param name="userLongitude">用户当前位置经度（可选）</param>
        /// <param name="userLatitude">用户当前位置纬度（可选）</param>
        /// <param name="searchKeyword">搜索关键词（可选）</param>
        /// <returns>院区列表</returns>
        [HttpGet]
        [ProducesResponseType(typeof(APIResult<List<HospitalAreaDto>>), 200)]
        public async Task<ActionResult<APIResult<List<HospitalAreaDto>>>> GetAllHospitalAreas(
            [FromQuery] decimal? userLongitude = null,
            [FromQuery] decimal? userLatitude = null,
            [FromQuery] string? searchKeyword = null)
        {
            try
            {
                _logger.LogInformation("接收到获取所有院区列表请求，搜索关键词：{SearchKeyword}，用户位置：({Latitude}, {Longitude})", 
                    searchKeyword, userLatitude, userLongitude);

                var query = new GetHospitalAreasQuery
                {
                    UserLongitude = userLongitude,
                    UserLatitude = userLatitude,
                    SearchKeyword = searchKeyword,
                    OnlySelfServiceEnabled = false // 获取所有院区
                };

                var result = await _mediator.Send(query);
                
                _logger.LogInformation("成功处理获取所有院区列表请求，返回 {Count} 个院区", result.Data?.Count ?? 0);
                
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理获取所有院区列表请求时发生错误");
                return StatusCode(500, new APIResult<List<HospitalAreaDto>>
                {
                    Code = APIEnum.Fail,
                    Message = "服务器内部错误，请稍后重试",
                    Data = new List<HospitalAreaDto>()
                });
            }
        }

        /// <summary>
        /// 根据ID获取院区详细信息
        /// </summary>
        /// <param name="id">院区ID</param>
        /// <returns>院区详细信息</returns>
        [HttpGet("{id}")]
        [ProducesResponseType(typeof(APIResult<HospitalAreaDto>), 200)]
        [ProducesResponseType(typeof(APIResult<HospitalAreaDto>), 404)]
        public async Task<ActionResult<APIResult<HospitalAreaDto>>> GetHospitalAreaById(int id)
        {
            try
            {
                _logger.LogInformation("接收到获取院区详细信息请求，院区ID：{Id}", id);

                // 创建查询，通过搜索关键词为ID的方式来复用现有逻辑
                var query = new GetHospitalAreasQuery
                {
                    OnlySelfServiceEnabled = false // 获取所有院区，不限制自助开单
                };

                var result = await _mediator.Send(query);
                
                if (result.Code == APIEnum.OK && result.Data != null)
                {
                    var hospitalArea = result.Data.FirstOrDefault(x => x.Id == id);
                    if (hospitalArea != null)
                    {
                        _logger.LogInformation("成功获取院区详细信息，院区ID：{Id}", id);
                        return Ok(new APIResult<HospitalAreaDto>
                        {
                            Code = APIEnum.OK,
                            Message = "获取院区信息成功",
                            Data = hospitalArea
                        });
                    }
                }

                _logger.LogWarning("未找到指定的院区，院区ID：{Id}", id);
                return NotFound(new APIResult<HospitalAreaDto>
                {
                    Code = APIEnum.Fail,
                    Message = "未找到指定的院区",
                    Data = default(HospitalAreaDto)! // 使用default!来避免null警告
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理获取院区详细信息请求时发生错误，院区ID：{Id}", id);
                return StatusCode(500, new APIResult<HospitalAreaDto>
                {
                    Code = APIEnum.Fail,
                    Message = "服务器内部错误，请稍后重试",
                    Data = default(HospitalAreaDto)! // 使用default!来避免null警告
                });
            }
        }
    }
}